package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.AgentAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.Agentbean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.wangchenlong.datescroller.widget.DateScrollerDialog;
import org.wangchenlong.datescroller.widget.data.Type;
import org.wangchenlong.datescroller.widget.listener.OnDateSetListener;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class AgentListActivity extends SwipeBackActivity implements View.OnClickListener,ListViewPlus.ListViewPlusListener{
    private String TAG="AgentListActivity";
    private int ageCode;
    private TextView show_time;
    private ListViewPlus mListView;
    private Agentbean mAgentbean;
    private AgentAdapter mAgentAdapter;
    private List<Agentbean> AgentbeanListBean = new ArrayList<>();
    private int page_count,count,page_index,stair_count;
    private LinearLayout imageView;
    private TextView textView,agent_find_text;
    private LinearLayout linearLayout;
    private String text="";
    private EditText find_agentList;


    private static final long HUNDRED_YEARS = 100L * 365 * 1000 * 60 * 60 * 24L;
    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM", Locale.ENGLISH);
    private long mLastTime = System.currentTimeMillis();
    private OnDateSetListener mOnDateSetListener = new OnDateSetListener() {
        @Override
        public void onDateSet(DateScrollerDialog timePickerView, long milliseconds) {
            mLastTime = milliseconds;
            text = getDateToString(milliseconds);
            //show_time.setText(text);
            Log.e(TAG, "text:"+text);
            findView(text);
        }
    };


    @Override
    public void onRefresh() {
        AgentbeanListBean.clear();
        intView();
        mAgentAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if(page_index<page_count){
             Log.e(TAG, "page_index:"+page_index);
            loadData(ListViewPlus.LOAD);
        }else{
            Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    Log.e(TAG, "onRefresh:");
                    //intView();
                    onLoadComplete();
                    Toast.makeText(getBaseContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    Log.e(TAG, "onLoadMore:");
                    loadMode(page_index,text);
                    break;
            }

        };
    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }
    private void loadMode(int page_index,String text) {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Userlist/agent_list");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("time", text);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ageCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String admin_name = value.getString("admin_name");
                        String uid = value.getString("uid");
                        String userpath = value.getString("userpath");
                        String user_tel = value.getString("user_tel");
                        String reg_time = value.getString("reg_time");
                        mAgentbean = new Agentbean(admin_name, uid, userpath, user_tel, reg_time);
                        AgentbeanListBean.add(mAgentbean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (ageCode == 200) {
                  //  mAgentAdapter = new AgentAdapter(getBaseContext().getApplicationContext(), AgentbeanListBean);
                    mAgentAdapter.notifyDataSetChanged();
                  //  mListView.setAdapter(mAgentAdapter);

//                    int i=AgentbeanListBean.size();
//                    textView.setText("("+i+"人)");
                }

                if (ageCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                onLoadComplete();
            }
        });

    }


    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.agent_list);
        mListView= (ListViewPlus) findViewById(R.id.agent_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);

        setStatusBar();
        agent_find_text= (TextView) findViewById(R.id.agent_find_text);
        show_time= (TextView) findViewById(R.id.show_agent_time);
        imageView= (LinearLayout) findViewById(R.id.agent_back);
        textView= (TextView) findViewById(R.id.show_agent_number);
        linearLayout= (LinearLayout) findViewById(R.id.show_list_agent);
        show_time.setOnClickListener(this);
        imageView.setOnClickListener(this);
        agent_find_text.setOnClickListener(this);
        find_agentList= (EditText) findViewById(R.id.find_agentList);
        find_agentList.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String name=find_agentList.getText().toString();
                AgentbeanListBean.clear();
                nameFind(name);

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        setListener();
        intView();

    }
    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListViewPlus listView = (ListViewPlus) parent;
                Agentbean mTanentBean = (Agentbean) listView.getItemAtPosition(position);
                String uid = mTanentBean.getUid();
                Intent Taxlistintent = new Intent(AgentListActivity.this, ListDetailsActivity.class);
                Taxlistintent.putExtra("uid", uid);
                startActivity(Taxlistintent);
            }
        });

    }
     private void findView(String s) {
        if(AgentbeanListBean !=null){
            AgentbeanListBean.clear();
        }
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Userlist/agent_list");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("time", s);
        params.addBodyParameter("page_size", 10);

        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ageCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                           count= jsonObjec.optInt("count", 0);
                           page_count= jsonObjec.optInt("page_count", 0);
                           page_index= jsonObjec.optInt("page_index", 0);
                           stair_count= jsonObjec.optInt("stair_count", 0);
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index +"  stair_count:"+stair_count);

                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String admin_name = value.getString("admin_name");
                        String uid = value.getString("uid");
                        String userpath = value.getString("userpath");
                        String user_tel = value.getString("user_tel");
                        String reg_time = value.getString("reg_time");
                        mAgentbean = new Agentbean(admin_name,uid,userpath,user_tel,reg_time);
                        AgentbeanListBean.add(mAgentbean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (ageCode == 200) {
                    mAgentAdapter = new AgentAdapter(getBaseContext().getApplicationContext(),AgentbeanListBean);
                    mAgentAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mAgentAdapter);

//                        int i=AgentbeanListBean.size();
//                        textView.setText("("+i+"人)");
                }

                if (ageCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                int i=AgentbeanListBean.size();
                if(i==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else{
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });
    }


    private void intView() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Userlist/agent_list");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ageCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)){
                        JSONObject jsonObjec = new JSONObject(data);
                           count= jsonObjec.optInt("count", 0);
                           page_count= jsonObjec.optInt("page_count", 0);
                           page_index= jsonObjec.optInt("page_index", 0);
                           stair_count= jsonObjec.optInt("stair_count", 0);
                           textView.setText("("+count+"人)");
                        Log.e(TAG, "count:"+count+"  page_count:"+page_count+"  page_index:"+page_index +"  stair_count:"+stair_count);
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String admin_name = value.getString("admin_name");
                        String uid = value.getString("uid");
                        String userpath = value.getString("userpath");
                        String user_tel = value.getString("user_tel");
                        String reg_time = value.getString("reg_time");
                        mAgentbean = new Agentbean(admin_name,uid,userpath,user_tel,reg_time);
                        AgentbeanListBean.add(mAgentbean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (ageCode == 200) {
                    mAgentAdapter = new AgentAdapter(getBaseContext().getApplicationContext(),AgentbeanListBean);
                    mAgentAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mAgentAdapter);

//                    int i=AgentbeanListBean.size();
//                    textView.setText("("+i+"人)");
                }

                if (ageCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                int i=AgentbeanListBean.size();
                if(i==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else{
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    private void nameFind(String name) {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/api/Userlist/agent_list");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("name", name);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                try {
                    JSONObject jsonObject = new JSONObject(result);
                    ageCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String admin_name = value.getString("admin_name");
                        String uid = value.getString("uid");
                        String userpath = value.getString("userpath");
                        String user_tel = value.getString("user_tel");
                        String reg_time = value.getString("reg_time");
                        mAgentbean = new Agentbean(admin_name,uid,userpath,user_tel,reg_time);
                        AgentbeanListBean.add(mAgentbean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (ageCode == 200) {
                    mAgentAdapter = new AgentAdapter(getBaseContext().getApplicationContext(),AgentbeanListBean);
                    mAgentAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mAgentAdapter);

//                    int i=AgentbeanListBean.size();
//                    textView.setText("("+i+"人)");
                }

                if (ageCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }else{


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
                int i=AgentbeanListBean.size();
                if(i==0){
                    linearLayout.setVisibility(View.VISIBLE);
                }else{
                    linearLayout.setVisibility(View.GONE);
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.agent_back:
                finish();
                break;
            case R.id.show_agent_time:
                shoewtime();
                 break;
            case R.id.agent_find_text:
                shoewtime();
                break;
        }
    }
    private void shoewtime() {
        DateScrollerDialog dialog = new DateScrollerDialog.Builder()
                .setType(Type.YEAR_MONTH)
                .setMinMilliseconds(System.currentTimeMillis() - HUNDRED_YEARS)
                .setMaxMilliseconds(System.currentTimeMillis())
                .setCurMilliseconds(mLastTime)
                .setCallback(mOnDateSetListener)
                .build();


        if (dialog != null) {
            if (!dialog.isAdded()) {
                dialog.show(getFragmentManager(), "year_month_day");
            }
        }


    }
    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

}
